package com.archgeek.java.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Set;

/**
 * @author pizhihui
 * @date 2024-06-14 23:50
 */
public class NioClientDemo {


    public static void main(String[] args) throws IOException {

        Selector selector = null;
        try {
            selector = Selector.open();
        } catch (Exception e) {
            throw e;
        }

        SocketChannel channel = null;
        try {

            channel = SocketChannel.open();

            channel.configureBlocking(false);

            Socket socket = channel.socket();
            socket.setSendBufferSize(512);
            socket.setReceiveBufferSize(512);

            socket.setTcpNoDelay(true);

            SocketAddress address = new InetSocketAddress(9765);

            // async
            boolean connected = channel.connect(address);
            System.out.println("connected: " + connected);


            SelectionKey key = channel.register(selector, SelectionKey.OP_CONNECT);

            key.attach(channel);


            int readKeys = selector.select();
            System.out.println("readKeys: " + readKeys);

            if (readKeys > 0) {
                Set<SelectionKey> selectionKeys = selector.selectedKeys();

                for (SelectionKey selectionKey : selectionKeys) {
                    System.out.println("selectionKey: " + selectionKey.isConnectable());
                    if (selectionKey.isConnectable()) {
                        System.out.println("连接成功...");
                        boolean b = channel.finishConnect();
                        if (b) {
                            key.interestOps(key.interestOps() & ~SelectionKey.OP_CONNECT | SelectionKey.OP_READ);
                        }
                    }
                    SelectableChannel channel1 = selectionKey.channel();

                }

            }


        } catch (Exception e) {
            throw e;
        } finally {
            if (null != channel) {
                try{
                    channel.close();
                } catch (Exception e){}
            }
        }



    }


}
